package com.shiwaixiangcun.monitor.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.shiwaixiangcun.core.exceptions.MonkeyException;
import com.shiwaixiangcun.core.plugin.dto.MonkeyDto;
import com.shiwaixiangcun.core.service.BaseServiceImpl;
import com.shiwaixiangcun.core.utils.MonkeyUtils;
import com.shiwaixiangcun.monitor.domain.ElectronicFence;
import com.shiwaixiangcun.monitor.dto.GeoLocationDto;
import com.shiwaixiangcun.monitor.repository.ElectronicFenceRepository;
import com.shiwaixiangcun.monitor.service.ElectronicFenceService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017-11-28.
 */
@Service
public class ElectronicFenceServiceImpl extends BaseServiceImpl<ElectronicFence, Long> implements ElectronicFenceService {
    @Autowired
    private ElectronicFenceRepository repository;

    @Override
    public void addElectronicFence(MonkeyDto monkeyDto) {
        List<ElectronicFence> electronicFenceList = repository.findAll();
        if (MonkeyUtils.isNotEmpty(electronicFenceList)) {
            for (ElectronicFence electronicFence : electronicFenceList) {
                repository.delete(electronicFence.getId());
            }
        }
        String electronicFence = monkeyDto.getString("electronicFence");
        if (MonkeyUtils.isNotEmpty(electronicFence)) {
            List<GeoLocationDto> locationDtoList = JSONArray.parseArray(electronicFence, GeoLocationDto.class);
            if (locationDtoList.size() < 3) {
                throw new MonkeyException("电子围栏最少要3个点");
            }
            for (GeoLocationDto geoLocationDto : locationDtoList) {
                ElectronicFence geoLocation = new ElectronicFence();
                BeanUtils.copyProperties(geoLocationDto, geoLocation);
                repository.save(geoLocation);
            }
        }
    }
    @Override
    public List<GeoLocationDto> getElectronicFence() {
        List<GeoLocationDto> geoLocationDtos = new ArrayList<>();
        List<ElectronicFence> electronicFenceList = repository.findAll();
        if (MonkeyUtils.isNotEmpty(electronicFenceList)) {

            for (ElectronicFence electronicFence : electronicFenceList) {
                GeoLocationDto geoLocationDto = new GeoLocationDto();
                BeanUtils.copyProperties(electronicFence, geoLocationDto);
                geoLocationDtos.add(geoLocationDto);
            }
        }
        return geoLocationDtos;
    }
}
